package cn.dakaqi.group.recruit.services;

import cn.dakaqi.entities.GroupRecruit;
import cn.dakaqi.entities.GroupRecruitVolunteer;
import cn.dakaqi.entities.GroupVolunteer;
import cn.dakaqi.entities.Volunteer;
import cn.dakaqi.group.services.GroupVolunteerService;
import cn.dakaqi.member.service.VolunteerService;
import cn.dakaqi.utils.Clock;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.ErrorCodeMsg;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import cn.dakaqi.utils.rongYun.PushGroupMesssage;
import cn.dakaqi.utils.rongYun.PushMessageUtil;
import cn.dakaqi.utils.rongYun.PushSystemMesssage;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chunyang on 2016/4/19.
 */
@Component(value = "groupRecruitVolunteerService")
@Transactional
public class GroupRecruitVolunteerServiceImpl implements GroupRecruitVolunteerService
{
    @Autowired
    GroupRecruitVolunteerDao groupRecruitVolunteerDao;
    @Autowired
    GroupRecruitService groupRecruitService;
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    GroupVolunteerService groupVolunteerService;

    @Override
    public void create(String param) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(param);
        String memberCode = jsonObject.getString("memberCode");
        Long groupRecruitId = jsonObject.getLong("groupRecruitId");
        String answer = jsonObject.getString("answer");
        String question = jsonObject.getString("question");

        //检查当前用户是否已报名本次招募
        GroupRecruitVolunteer groupRecruitVolunteer =  this.isApply(groupRecruitId,memberCode);
        if(null != groupRecruitVolunteer)
        {
            if(groupRecruitVolunteer.getStatus() == DKQConstant.APPLY_STATUS)
                throw new ServiceRuntimeException("请耐心等待管理员审核");
            else
            {
                groupRecruitVolunteer.setStatus(DKQConstant.APPLY_STATUS);
                groupRecruitVolunteer.setCreateTime(Clock.DEFAULT.getCurrentDate());
            }
        }
        else
        {
            groupRecruitVolunteer = new GroupRecruitVolunteer();
            groupRecruitVolunteer.setStatus(DKQConstant.APPLY_STATUS);
            groupRecruitVolunteer.setCreateTime(Clock.DEFAULT.getCurrentDate());
            groupRecruitVolunteer.setGroupRecruit(this.groupRecruitService.findOne(groupRecruitId));

            Volunteer volunteer = this.volunteerService.findByMemberCode(memberCode);
            if(Volunteer.checkInfo(volunteer) == false)
                throw new ServiceRuntimeException(ErrorCodeMsg.USER_INFO_NOT_FULL);

            groupRecruitVolunteer.setVolunteer(volunteer);
            groupRecruitVolunteer.setAnswer(answer);
            groupRecruitVolunteer.setQuession(question);
        }
        save(groupRecruitVolunteer);
    }

    @Override
    public void save(GroupRecruitVolunteer groupRecruitVolunteer)throws ServiceRuntimeException
    {
        //检查当前用户是否是当前社团的成员
        GroupVolunteer temp = groupVolunteerService.findByMemberAndGroup(groupRecruitVolunteer.getVolunteer().getMemberCode(),DKQConstant.APPLY_STATUS_ALL , groupRecruitVolunteer.getGroupRecruit().getGroup().getGroupCode());
        if(temp != null && temp.getStatus() == DKQConstant.APPLY_STATUS_OK)
            throw new ServiceRuntimeException("您已是本社团成员,不可以报名本次招募");

        groupRecruitVolunteerDao.save(groupRecruitVolunteer);
        GroupRecruit groupRecruit = groupRecruitVolunteer.getGroupRecruit();
        groupRecruit.setApplys(groupRecruit.getApplys()+1);
        this.groupRecruitService.update(groupRecruit);
        PushGroupMesssage.getInstance().applyGroupRecruit(groupRecruitVolunteer.getGroupRecruit().getGroup().getName(),groupRecruitVolunteer.getVolunteer().getMemberCode());
        PushGroupMesssage.getInstance().waiteVerfierGroupReuitelunteer(groupRecruitVolunteer.getGroupRecruit().getGroup().getName(),groupRecruitVolunteer.getVolunteer().getRealName(),groupRecruitVolunteer.getVolunteer().getMemberCode(),groupRecruitVolunteer.getGroupRecruit().getVolunteer().getMemberCode(),groupRecruitVolunteer.getId());
    }

    @Override
    public Page<GroupRecruitVolunteer> findAll(Long groupRecruitId, int pageNumber)throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(pageNumber - 1, 20, sort);
        Map<String,Object> map = new HashMap<String, Object>();
        //map.put("LIKE_NAME",name);
        //Map<String, SearchFilter> filters = SearchFilter.parse(map);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("groupRecruit.id", new SearchFilter("groupRecruit.id", SearchFilter.Operator.EQ, groupRecruitId));
        Specification<GroupRecruitVolunteer> spec = DynamicSpecifications.bySearchFilter(filters.values(), GroupRecruitVolunteer.class);
        return this.groupRecruitVolunteerDao.findAll(spec,pageRequest);
    }

    @Override
    public Page<GroupRecruitVolunteer> findByGroupRecruit(Long groupRecruitId, int status, int pageNumber)throws ServiceRuntimeException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(pageNumber - 1, 20, sort);

        //Map<String,Object> map = new HashMap<String, Object>();
        //map.put("LIKE_NAME",name);
        //Map<String, SearchFilter> filters = SearchFilter.parse(map);

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("groupRecruit.id", new SearchFilter("groupRecruit.id", SearchFilter.Operator.EQ, groupRecruitId));
        filters.put("status", new SearchFilter("status", SearchFilter.Operator.EQ, status));
        Specification<GroupRecruitVolunteer> spec = DynamicSpecifications.bySearchFilter(filters.values(), GroupRecruitVolunteer.class);
        return this.groupRecruitVolunteerDao.findAll(spec,pageRequest);
    }

    @Override
    public List<GroupRecruitVolunteer> findVerfierByGroupRecruit(Long groupRecruitId, int status, int pageNumber) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("groupRecruit.id", new SearchFilter("groupRecruit.id", SearchFilter.Operator.EQ, groupRecruitId));
        filters.put("status", new SearchFilter("status", SearchFilter.Operator.EQ, status));
        Specification<GroupRecruitVolunteer> spec = DynamicSpecifications.bySearchFilter(filters.values(), GroupRecruitVolunteer.class);
        return this.groupRecruitVolunteerDao.findAll(spec);
    }

    @Override
    public List<GroupRecruitVolunteer> findVerfierByGroup(String groupCode, int status, int pageNumber) throws ServiceRuntimeException
    {
        //查询当前社团正在进行的招募
        GroupRecruit groupRecruit = this.groupRecruitService.findLastByGroupCode(groupCode,DKQConstant.PROCEED_START);
        if(null == groupRecruit)
            return null;

        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("groupRecruit.group.groupCode", new SearchFilter("groupRecruit.group.groupCode", SearchFilter.Operator.EQ, groupCode));
        filters.put("groupRecruit.status", new SearchFilter("groupRecruit.status", SearchFilter.Operator.EQ, DKQConstant.PROCEED_START));
        filters.put("status", new SearchFilter("status", SearchFilter.Operator.EQ, status));
        Specification<GroupRecruitVolunteer> spec = DynamicSpecifications.bySearchFilter(filters.values(), GroupRecruitVolunteer.class);
        return this.groupRecruitVolunteerDao.findAll(spec);

    }

    @Override
    public void updateVerfierStatus(Long groupRecruitVolunteerId, String memberCode,int status,String refuseCase)throws ServiceRuntimeException
    {
        GroupRecruitVolunteer groupRecruitVolunteer = this.groupRecruitVolunteerDao.findOne(groupRecruitVolunteerId);
        if(groupRecruitVolunteer != null)
        {
            groupRecruitVolunteer.setStatus(status);
            this.groupRecruitVolunteerDao.save(groupRecruitVolunteer);
            if(status == DKQConstant.APPLY_STATUS_OK)
            {
                //查询当前用户是否已是本社团成员
                GroupVolunteer temp = this.groupVolunteerService.findByMemberAndGroup(groupRecruitVolunteer.getVolunteer().getMemberCode(),DKQConstant.APPLY_STATUS_ALL ,groupRecruitVolunteer.getGroupRecruit().getGroup().getGroupCode());
                if(null != temp)
                    throw new ServiceRuntimeException("该用户已是本社团成员,不可以重复加入!");
                GroupVolunteer groupVolunteer = new GroupVolunteer();
                groupVolunteer.setVolunteer(groupRecruitVolunteer.getVolunteer());
                groupVolunteer.setGroup(groupRecruitVolunteer.getGroupRecruit().getGroup());
                groupVolunteer.setCreateTime(Clock.DEFAULT.getCurrentDate());
                groupVolunteer.setRole(DKQConstant.ROLES_VOLUNTEER);
                groupVolunteer.setStatus(DKQConstant.APPLY_STATUS_OK);
                groupVolunteer.setGroup(groupRecruitVolunteer.getGroupRecruit().getGroup());
                this.groupVolunteerService.save(groupVolunteer);

                PushGroupMesssage.getInstance().agreeGroupRecruit(groupVolunteer.getGroup().getName(),groupVolunteer.getVolunteer().getMemberCode());
            }
            else if(status == DKQConstant.APPLY_STATUS_REFUST)
            {
                groupRecruitVolunteer.setRefuseCase(groupRecruitVolunteer.getRefuseCase()+"|"+refuseCase);
                PushSystemMesssage.getInstance().refuseGroupRecruit(groupRecruitVolunteer.getGroupRecruit().getGroup().getName(),groupRecruitVolunteer.getVolunteer().getMemberCode());
//                //推送消息至志愿者用户
//                List<String> volunteers = new ArrayList<String>();
//                volunteers.add(groupRecruitVolunteer.getVolunteer().getMemberCode());
//                PushMessageUtil.publishSystemMessage(groupRecruitVolunteer.getGroupRecruit().getGroup().getName() + "招募拒绝了您的申请。", null, PushMessageUtil.SYSTEM_HELPER, volunteers);
            }
        }
    }

    @Override
    public GroupRecruitVolunteer findOne(Long groupRecruitVolunteerId) throws ServiceRuntimeException
    {
        return groupRecruitVolunteerDao.findOne(groupRecruitVolunteerId);
    }

    @Override
    public void updateVerfierStatus(String param)throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(param);
        Long groupRecruitVolunteerId = jsonObject.getLong("groupRecruitVolunteerId");
        String memberCode = jsonObject.getString("memberCode");
        String refuseCase = jsonObject.getString("refuseCase");
        int status = jsonObject.getIntValue("status");
        this.updateVerfierStatus(groupRecruitVolunteerId,memberCode,status,refuseCase);
    }

    @Override
    public void exit(String param) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(param);
        Long groupRecruitVolunteerId = jsonObject.getLong("groupRecruitVolunteerId");
        GroupRecruitVolunteer groupRecruitVolunteer = findOne(groupRecruitVolunteerId);
        exit(groupRecruitVolunteer);
    }

    @Override
    public void exit(GroupRecruitVolunteer groupRecruitVolunteer) throws ServiceRuntimeException
    {
        if(null == groupRecruitVolunteer)
            return;
        //更新报名人数
        GroupRecruit groupRecruit = groupRecruitVolunteer.getGroupRecruit();
        groupRecruit.setApplys(groupRecruit.getApplys()-1);
        this.groupRecruitService.update(groupRecruit);
        //删除记录
        groupRecruitVolunteerDao.delete(groupRecruitVolunteer);
    }

    @Override
    public GroupRecruitVolunteer isApply(Long groupRecruitId, String memberCode) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("groupRecruit.id", new SearchFilter("groupRecruit.id", SearchFilter.Operator.EQ, groupRecruitId));
        filters.put("volunteer.memberCode", new SearchFilter("volunteer.memberCode", SearchFilter.Operator.EQ, memberCode));
        Specification<GroupRecruitVolunteer> spec = DynamicSpecifications.bySearchFilter(filters.values(), GroupRecruitVolunteer.class);
        List<GroupRecruitVolunteer> list =  this.groupRecruitVolunteerDao.findAll(spec);
        if(null != list && list.size()>0)
            return list.get(0);

        return null;
    }
}
